package com.ygr.anime.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.dev33.satoken.util.SaResult;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.ygr.anime.domain.Anime;
import com.ygr.anime.domain.AnimeUrl;
import com.ygr.anime.dto.AnimeDto;
import com.ygr.anime.service.AnimeService;
import com.ygr.anime.service.AnimeUrlService;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

@RestController
@AllArgsConstructor
@RequestMapping("/anime")
class AnimeController {

    private final AnimeService animeService;
    private final AnimeUrlService animeUrlService;


    @SaCheckLogin
    @GetMapping("/list")
    public SaResult list() {
        List<AnimeDto> animeDtoList = new ArrayList<>();

        for (Anime anime : animeService.list()) {
            animeDtoList.add(AnimeDto.builder()
                    .id(anime.getId())
                    .title(anime.getTitle())
                    .image(anime.getImage())
                    .createdAt(anime.getCreatedAt())
                    .updatedAt(anime.getUpdatedAt())
                    .build());
        }

        return SaResult.ok("获取动漫列表成功").setData(animeDtoList);
    }

    @SaCheckLogin
    @GetMapping("/detail/{id}")
    public SaResult get(@PathVariable Long id) {
        Anime anime = animeService.getById(id);
        List<AnimeUrl> animeUrls = animeUrlService.listByMap(Map.of("anime_id", id));
        return SaResult.ok("获取动漫信息成功").setData(
                AnimeDto.builder()
                        .id(anime.getId())
                        .title(anime.getTitle())
                        .image(anime.getImage())
                        .intro(anime.getIntro())
                        .createdAt(anime.getCreatedAt())
                        .updatedAt(anime.getUpdatedAt())
                        .datasource(animeUrls)
                        .build()
        );
    }

    @SaCheckLogin
    @GetMapping("/player/{animeId}")
    public SaResult getUrl(@PathVariable Long animeId, @RequestParam Integer id) {
        List<AnimeUrl> animeUrls = animeUrlService.listByMap(
                Map.of("anime_id", animeId, "id", id)
        );
        return SaResult.ok("获取播放源成功").setData(animeUrls);
    }

}
